package dongshi.daddy.encryptionAndDecryption.rsa;

import org.apache.commons.codec.binary.Base64;

public class Signature {

    public static void main(String[] args) {
        try {
            Info info = new Info();
            String needSendMsg = "我已经到北京了";
            info.setMsg(needSendMsg);
            // 生成摘要
            String digest = Md5Utils.md5(needSendMsg);
            System.out.println("发送方摘要：" + digest);
            info.setDigest(digest);
            // 生成数字签名
            byte[] signatureByte = RsaUtil.encryptByPrivateKey(digest.getBytes());
            String senderSignature = Base64.encodeBase64String(signatureByte);
            info.setSignature(senderSignature);
            System.out.println("发送方签名：" + senderSignature);


            // 接收方行为模拟
            String receiveMsg = info.getMsg();
            String receiveDigest = info.getDigest();
            String receiveSignature = info.getSignature();
            // 解密数字签名获取摘要
            String encyptDigest
                    = RsaUtil.decryptByPublicKey(Base64.decodeBase64(receiveSignature));
            String generateDigest = Md5Utils.md5(receiveMsg);
            System.out.println("接收方解密的摘要：" + encyptDigest + ", 通过原始消息生成的摘要是：" + generateDigest);
            if (encyptDigest.equalsIgnoreCase(generateDigest)) {
                System.err.println("摘要一致，消息正常！");
                System.err.println("消息【" + info.getMsg() + "】,成功传输！！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
